//
//  OAuthViewController.swift
//  Status
//
//  Created by 花轮 on 15/5/12.
//  Copyright (c) 2015年 花轮. All rights reserved.
//

import UIKit
import SVProgressHUD

class OAuthViewController: UIViewController, UIWebViewDelegate {
    
    let WB_Client_Id = "1895699203"
    let WB_Redirect_Uri = "http://itheima.com"
    let WB_Client_Secret = "b517c73e78aeaf85891c7733de012988"
    
    var webView: UIWebView{
        return view as! UIWebView
    }
    
    @IBAction func backClick(){
        SVProgressHUD.dismiss()
        dismissViewControllerAnimated(true, completion: nil)
    }

    
    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated)

        loadAuthPage()
    }
    
    private func loadAccessToken(code: String)
    {
        let params = [
            "client_id":WB_Client_Id,
            "client_secret":WB_Client_Secret,
            "grant_type":"authorization_code",
            "code":code,
            "redirect_uri":WB_Redirect_Uri,]
        UserAccount.loadAccessToken(params) { (account) in
            if account != nil
            {
                sharedUserAccount = account
//                println("账户信息\( account)")
                
                NSNotificationCenter.defaultCenter().postNotificationName(LKSwitchRootViewControllerNotification, object: "Welcome")
                self.dismissViewControllerAnimated(true, completion: nil)
                return
            }
        }
    }

    private func loadAuthPage()
    {
        let urlStr = "https://api.weibo.com/oauth2/authorize?client_id=" + WB_Client_Id + "&redirect_uri=" + WB_Redirect_Uri
        
        let url = NSURL(string: urlStr)!
        
        webView.loadRequest(NSURLRequest(URL: url))
    }
    
    /**
    1 https://api.weibo.com/
    2 授权成功 http://itheima.com/?code=fefca19bdc0d0257725478373ab9a373
    3 http://m.weibo.cn/reg/index
    4 http://login.sina.com.cn/sso/
    5 用户取消授权 http://itheima.com/?error_uri=
    */
    
    // 如果系统方法返回 Bool  返回true 都能工作正常
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        
        let urlStr = request.URL!.absoluteString!
        
//        println(urlStr)
        
        if urlStr.hasPrefix("https://api.weibo.com/")
        {
            return true
        }
        
        if !urlStr.hasPrefix(WB_Redirect_Uri)
        {
            return false
        }
        
//        println("--------" + request.URL!.query!)
        
        let codeStr = "code="
        
        let query = request.URL!.query!
//        println(query)
        if query.hasPrefix(codeStr)
        {
            let code = (query as NSString).substringFromIndex(codeStr.lengthOfBytesUsingEncoding(NSUTF8StringEncoding))
//            println("验证码" + code)
            loadAccessToken(code)
        }
        else
        {
//            println("用户拒绝")
            backClick()
        }
        
        return false
    }
    
    
    func webViewDidStartLoad(webView: UIWebView) {
        SVProgressHUD.show()
    }
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
}
